package com.study.jyg.rxjava2study.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.SystemClock;
import android.telephony.TelephonyManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.study.jyg.rxjava2study.MyApplication;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SystemUtil {


    /**
     * 获取序列号
     *
     * @return
     */
    public static void getSerialNumber(AppCompatActivity activity, SystemListener listener) {
        RxPermissionUtil.initPermission(activity, 101, () -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                try {
                    if (listener != null)
                        listener.success(Build.getSerial());
                } catch (Exception e) {
                    e.printStackTrace();
                    listener.success(null);
                }
            } else {
                if (listener != null)
                    listener.success(Build.SERIAL);
            }
        }, Manifest.permission.READ_PHONE_STATE);
    }

    /**
     * 获取手机号
     *
     * @param activity
     * @param listener
     */
    @SuppressLint({"MissingPermission", "HardwareIds"})
    public static void getPhoneNumb(AppCompatActivity activity, SystemListener listener) {
        RxPermissionUtil.initPermission(activity, 101, () -> {
            TelephonyManager tm = (TelephonyManager) activity.getSystemService(Context.TELEPHONY_SERVICE);
            String phoneNumb = tm.getLine1Number();
            if (phoneNumb.contains("+86"))
                phoneNumb = phoneNumb.replace("+86", "");
            if (listener != null)
                listener.success(phoneNumb);
        }, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_SMS, Manifest.permission.READ_PHONE_NUMBERS);
    }

    /**
     * 获取mac地址（使用linux命令）
     *
     * @return
     */
    public static String getLocalMac() {
        String mac = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str; ) {
                str = input.readLine();
                if (str != null) {
                    mac = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return mac;

    }

    public static void getMacAddress(final Activity ac, final SystemListener callback) {
        final WifiManager wm = (WifiManager) MyApplication.getAppContext().getApplicationContext().getSystemService(Service.WIFI_SERVICE);
        // 如果本次开机后打开过WIFI，则能够直接获取到mac信息。立刻返回数据。
        WifiInfo info = wm.getConnectionInfo();
        if (info != null && info.getMacAddress() != null) {
            if (callback != null) {
                callback.success(info.getMacAddress());
            }
            return;
        }
        // 尝试打开WIFI，并获取mac地址
        if (!wm.isWifiEnabled()) {
            wm.setWifiEnabled(true);
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                int tryCount = 0;
                final int MAX_COUNT = 10;
                while (tryCount < MAX_COUNT) {
                    final WifiInfo info = wm.getConnectionInfo();
                    if (info != null && info.getMacAddress() != null) {
                        if (callback != null) {
                            ac.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    callback.success(info.getMacAddress());
                                }
                            });
                        }
                        return;
                    }
                    SystemClock.sleep(300);
                    tryCount++;
                }
                // 未获取到mac地址
                if (callback != null) {
                    callback.success(null);
                }
            }
        }).start();
    }


    public static String getBtAddressByReflection() {
        BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        Field field = null;

        try {
            field = BluetoothAdapter.class.getDeclaredField("mService");

            field.setAccessible(true);

            Object bluetoothManagerService = field.get(bluetoothAdapter);

            if (bluetoothManagerService == null) {
                return null;

            }

            Method method = bluetoothManagerService.getClass().getMethod("getAddress");

            if (method != null) {
                Object obj = method.invoke(bluetoothManagerService);

                if (obj != null) {
                    return obj.toString();

                }

            }

        } catch (NoSuchFieldException e) {
            e.printStackTrace();

        } catch (IllegalAccessException e) {
            e.printStackTrace();

        } catch (NoSuchMethodException e) {
            e.printStackTrace();

        } catch (InvocationTargetException e) {
            e.printStackTrace();

        }

        return null;

    }

    public interface SystemListener {
        void success(String... strs);
    }

    /**
     * 获取电池电量
     * @param context
     * @return
     */
    public static int getSystemBattery(Context context) {
        int level = 0;
        Intent batteryInfoIntent = context.getApplicationContext().registerReceiver(null,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        level = batteryInfoIntent.getIntExtra("level", 0);
        int batterySum = batteryInfoIntent.getIntExtra("scale", 100);
        int percentBattery = 100 * level / batterySum;
        return percentBattery;
    }
}
